<template>
  <div class="app-container">
    <el-form
      class="elForm"
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-if="showSearch"
      label-width="150px"
    >
      <el-form-item :label="$t('notice.title')" prop="noticeTitle">
        <el-input
          v-model="queryParams.noticeTitle"
          :placeholder="$t('notice.PleaseEnterTheAnnouncementTitle')"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('notice.operaror')" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          :placeholder="$t('notice.PleaseEnterOperator')"
          clearableimage.png
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('notice.announcementType')" prop="noticeType">
        <el-select
          v-model="queryParams.noticeType"
          :placeholder="$t('common.pleaseSelect')"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >{{ $t("common.search") }}</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
          $t("common.reset")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >{{ $t("common.addButton") }}</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="noticeList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        :label="$t('notice.serialNo')"
        align="center"
        prop="noticeId"
        width="100"
      />
      <el-table-column
        :label="$t('notice.title')"
        align="center"
        prop="noticeTitle"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="$t('notice.announcementType')"
        align="center"
        prop="noticeType"
        :formatter="typeFormat"
        width="130"
      />
      <el-table-column
        :label="$t('notice.status')"
        align="center"
        prop="status"
        :formatter="statusFormat"
        width="100"
      />
      <el-table-column
        :label="$t('notice.creator')"
        align="center"
        prop="createBy"
        width="100"
      />
      <el-table-column
        :label="$t('notice.creationTime')"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('common.operation')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >{{ $t("common.edit") }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >{{ $t("common.del") }}</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            >{{ $t("common.details") }}</el-button
          >
          <!-- <svg-icon :icon-class="icon" /> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-copy-document"
            @click="
              copyToClipboard(
                baseUrl.slice(0, baseUrl.indexOf('/', 7) + 1) +
                  'content/index.html?id=' +
                  scope.row.noticeId
              )
            "
            >{{ $t("common.copyLink") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="818px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        :class="{ showDisabledClas: title == $t('common.details') }"
      >
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item
              v-if="
                +form.noticeType !== 2 &&
                +form.noticeType !== 1 &&
                typeof form.noticeType !== 'undefind'
              "
              :label="$t('notice.title')"
              prop="noticeTitle"
            >
              <el-input
                v-model="form.noticeTitle"
                :disabled="title == $t('common.details')"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item
              :label="$t('notice.announcementType')"
              prop="noticeType"
            >
              <el-select
                v-model="form.noticeType"
                :placeholder="$t('common.pleaseSelect')"
                :disabled="title == $t('common.details')"
              >
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('notice.status')" prop="status">
              <el-radio-group
                v-model="form.status"
                :disabled="title == $t('common.details')"
              >
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.noticeType == '2'">
            <!-- <el-form-item label="插图" prop="illustration">
              <cropper-modal
                v-if="open"
                @getImageUrl="getImageUrl"
                :fixed-number="[1.6, 1]"
                :image-url="form.illustration"
                :current-handle="title"
              /> -->

            <!--              <image-miner-upload v-if="open"  :value="form.illustration" @input="getImageUrl" :current-handle="title" :image-width="393" :image-height="243"/>-->
            <!-- </el-form-item> -->
          </el-col>
          <el-col :span="24" v-if="form.noticeType == '1'">
            <el-form-item :label="$t('notice.cover')" prop="illustration">
              <cropper-modal
                v-if="open"
                @getImageUrl="getImageUrl"
                :fixed-number="[1.568, 1]"
                :image-url="form.illustration"
                :current-handle="title"
              />

              <!--              <image-miner-upload v-if="open"  :value="form.illustration" @input="getImageUrl" :current-handle="title" :image-width="393" :image-height="243"/>-->
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item
              prop="noticeSource"
              :label="$t('notice.infomationType')"
              v-if="form.noticeType == '1' || form.noticeType == '3'"
            >
              <el-radio-group
                v-model="form.noticeSource"
                :disabled="title == $t('common.details')"
              >
                <el-radio
                  v-for="item in informationTypeOptions"
                  :key="item.val"
                  :label="item.val"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
              <!-- <el-switch
                v-model="form.informationType"
                active-value="1"
                inactive-value="0"
              ></el-switch> -->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="$t('notice.link')"
              prop="linkUrl"
              v-if="
                form.noticeType == '3' ||
                (form.noticeType == '1' && form.noticeSource === 'out')
              "
            >
              <el-input
                v-model="form.linkUrl"
                :disabled="title == $t('common.details')"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              :label="$t('notice.internationalizationConfiguration')"
              v-if="
                (form.noticeType == '1' && form.noticeSource === 'inner') ||
                form.noticeType == '2'
              "
            >
              <el-tabs v-model="activeTab" type="border-card">
                <el-tab-pane :label="$t('common.chinese')" name="中文">
                  <el-row :gutter="10">
                    <el-col :span="24">
                      <span>{{ $t("notice.title") }}</span>
                    </el-col>
                    <el-col :span="24">
                      <el-input
                        v-model="form.noticeI18nList[0].noticeTitle"
                        :disabled="title == $t('common.details')"
                        :placeholder="$t('common.pleaseEnter')"
                      />
                    </el-col>
                    <el-col :span="24">
                      <span>{{ $t("notice.content") }}</span>
                    </el-col>
                    <el-col :span="24">
                      <editor
                        v-model="form.noticeI18nList[0].noticeContent"
                        :read-only="title == $t('common.details')"
                        :min-height="192"
                      />
                    </el-col>
                  </el-row>
                </el-tab-pane>
                <el-tab-pane :label="$t('common.english')" name="英文">
                  <el-row :gutter="10">
                    <el-col :span="24">
                      <span>{{ $t("notice.title") }}</span>
                    </el-col>
                    <el-col :span="24">
                      <el-input
                        v-model="form.noticeI18nList[1].noticeTitle"
                        :disabled="title == $t('common.details')"
                        :placeholder="$t('common.pleaseEnter')"
                      />
                    </el-col>
                    <el-col :span="24">
                      <span>{{ $t("notice.content") }}</span>
                    </el-col>
                    <el-col :span="24">
                      <editor
                        v-model="form.noticeI18nList[1].noticeContent"
                        :read-only="title == $t('common.details')"
                        :min-height="192"
                      />
                    </el-col>
                  </el-row>
                </el-tab-pane>
                <el-tab-pane :label="$t('common.thai')" name="泰文">
                  <el-row :gutter="10">
                    <el-col :span="24">
                      <span>{{ $t("notice.title") }}</span>
                    </el-col>
                    <el-col :span="24">
                      <el-input
                        v-model="form.noticeI18nList[2].noticeTitle"
                        :disabled="title == $t('common.details')"
                        :placeholder="$t('common.pleaseEnter')"
                      />
                    </el-col>
                    <el-col :span="24">
                      <span>{{ $t("notice.content") }}</span>
                    </el-col>
                    <el-col :span="24">
                      <editor
                        v-model="form.noticeI18nList[2].noticeContent"
                        :read-only="title == $t('common.details')"
                        :min-height="192"
                      />
                    </el-col>
                  </el-row>
                </el-tab-pane>
              </el-tabs>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        v-if="title != $t('common.details')"
      >
        <el-button type="primary" @click="submitForm">{{
          $t("common.confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("common.cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listNotice, getNotice, delNotice, addNotice, updateNotice, exportNotice } from "@/api/system/notice";
import Editor from '@/components/Editor';
// import ImageMinerUpload from '@/components/ImageMinerUpload'
import CropperModal from '@/components/CropperModal'

import { validURL } from "@/utils/validate";


export default {
  name: "Notice",
  components: {
    Editor,
    CropperModal
    // ImageMinerUpload
  },
  data () {
    const validFormURL = (rule, value, callback) => {
      if (!validURL(value)) {
        callback(new Error(this.$t('notice.incorrectLinkFormat')));
      } else {
        callback();
      }
    };
    return {
      informationTypeOptions: [
        { val: 'inner', label: this.$t('notice.innerLink') },
        { val: 'out', label: this.$t('notice.outerLink') },
      ],
      activeTab: '中文',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      noticeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      statusOptions: [],
      // 状态数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        createBy: undefined,
        noticeType: undefined
      },
      // 表单参数
      form: {
        noticeSource: 'inner',
        noticeI18nList: [
          {
            language: 'zh',
            noticeTitle: '',
            noticeContent: ''
          },
          {
            language: 'en',
            noticeTitle: '',
            noticeContent: ''
          },
          {
            language: 'th',
            noticeTitle: '',
            noticeContent: ''
          },
        ]
      },
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: this.$t('common.cannotBeEmpty'), trigger: "blur" }
        ],
        noticeType: [
          { required: true, message: this.$t('common.cannotBeEmpty'), trigger: "blur" }
        ],
        status: [
          { required: true, message: this.$t('common.cannotBeEmpty'), trigger: "blur" }
        ],
        illustration: [
          { required: true, message: this.$t('common.cannotBeEmpty'), trigger: "blur" }
        ],
        noticeSource: [
          { required: true, message: this.$t('common.cannotBeEmpty'), trigger: "blur" }
        ],
        noticeContent: [
          { required: true, message: this.$t('common.cannotBeEmpty'), trigger: "blur" }
        ],
        linkUrl: [
          { required: true, message: this.$t('common.cannotBeEmpty'), trigger: "blur" },
          { required: true, validator: validFormURL, trigger: "blur" }
        ],
        // illustration: [
        //   { required: true, message: "请上传图片", trigger: "blur" }
        // ],
        // noticeType: [
        //   { required: true, message: this.$t('common.cannotBeEmpty'), trigger: "change" }
        // ]
      }
    };
  },
  created () {
    this.getList();
    this.getDicts("sys_notice_status").then(response => {
      this.statusOptions = response;
    });
    this.getDicts("sys_notice_type").then(response => {
      console.log('sys_notice_type', response)
      this.typeOptions = response;
      // this.typeOptions = [
      //   { dictLabel: '资讯', dictValue: '1' },
      //   { dictLabel: '公告', dictValue: '2' }
      // ]
    });
  },
  methods: {
    copyToClipboard (text) {
      // console.log('text', text)
      this.copy(text)
    },
    fallbackCopyTextToClipboard (text) {
      // 1.创建一个可选中元素
      let textArea = document.createElement("textarea");
      textArea.value = window.location.href;
      // 2.使用定位，阻止页面滚动
      textArea.style.top = "0";
      textArea.style.left = "0";
      textArea.style.height = "200px";
      textArea.style.width = "200px";
      textArea.style.position = "fixed";
      textArea.innerText = text;
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Fallback: Copying text command was ' + msg);
      } catch (err) {
        console.error('Fallback: Oops, unable to copy', err);
      }
      // 3.移除元素
      document.body.removeChild(textArea);
    },
    copyTextToClipboard (text) {
      const that = this
      console.log('text', text)
      if (!window.navigator.clipboard) {
        this.fallbackCopyTextToClipboard(text);
        return;
      }
      window.navigator.clipboard.writeText(text).then(function () {
        // console.log('Async: Copying to clipboard was successful!');
        // this.$message({
        //   message: this.msgSuccess(this.$t('common.copySuccessTip')),
        //   type: 'success'
        // })
        that.$message({
          message: that.$t('common.copySuccessTip'),
          type: 'success'
        })
      }, function (err) {
        // console.error('Async: Could not copy text: ', err);
        that.$message({
          message: that.$t('common.copyFailTip'),
          type: 'error'
        })
      });
    },
    getImageUrl (message) {
      this.form.illustration = ''
      if (message) {
        this.form.illustration = message
      }
    },
    /** 查询公告列表 */
    getList () {
      this.loading = true;
      listNotice(this.queryParams).then(response => {
        this.noticeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 公告状态字典翻译
    statusFormat (row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 公告状态字典翻译
    typeFormat (row, column) {
      return this.selectDictLabel(this.typeOptions, row.noticeType);
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      // this.form = {
      //   noticeId: undefined,
      //   noticeTitle: undefined,
      //   noticeType: undefined,
      //   noticeContent: undefined,
      //   linkUrl: undefined,
      //   illustration: undefined,
      //   status: "0"
      // };
      // delete this.form.illustration
      // console.log('444')
      // this.form = {
      //   createBy: undefined,
      //   createTime: undefined,
      //   illustration: undefined,
      //   linkUrl: undefined,
      //   noticeContent: undefined,
      //   noticeId: undefined,
      //   noticeTitle: undefined,
      //   noticeType: undefined,
      //   params: undefined,
      //   remark: null,
      //   searchValue: null,
      //   status: undefined,
      //   updateBy: undefined,
      //   updateTime: undefined,
      // }
      this.form = {
        illustration: "",
        linkUrl: "",
        noticeI18nList: [
          {
            language: 'zh',
            noticeTitle: '',
            noticeContent: ''
          },
          {
            language: 'en',
            noticeTitle: '',
            noticeContent: ''
          },
          {
            language: 'th',
            noticeTitle: '',
            noticeContent: ''
          },
        ],
        noticeSource: "",
        noticeType: "",
        status: ""
      }
      this.$forceUpdate()
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.noticeId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      // console.log('222 ')
      this.reset();
      this.open = true;
      this.title = this.$t('common.addTitle');
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const noticeId = row.noticeId || this.ids
      getNotice(noticeId).then(response => {
        this.form = response;
        this.open = true;
        this.title = this.$t('common.edit');
      });
    },
    /** 查看公告详情 */
    handleView (row) {
      this.reset();
      const noticeId = row.noticeId
      getNotice(noticeId).then(response => {
        this.form = response;
        this.open = true;
        this.title = this.$t('common.details');
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.noticeId != undefined) {
            updateNotice(this.form).then(response => {
              this.msgSuccess(this.$t('common.modifySuccessfully'));
              this.open = false;
              this.getList();
            });
          } else {
            addNotice(this.form).then(response => {
              this.msgSuccess(this.$t('common.addedSuccessfully'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const noticeIds = row.noticeId || this.ids
      this.$confirm(this.$t('notice.delTip') + noticeIds + ' ?', this.$t('common.warning'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: "warning"
      }).then(function () {
        return delNotice(noticeIds);
      }).then(() => {
        this.getList();
        this.msgSuccess(this.$t('common.successfullyDeleted'));
      })
    }
  }
};
</script>
<style lang='scss'>
.showDisabledClas {
  .el-input.is-disabled .el-input__inner {
    color: #606266;
  }
}
// .el-form-item__label {
//   /* // margin-left: 0px !important; */
//   // background-color: #ff0000 !important;
//   word-break: break-word;
// }
</style>
